package com.sourceQ.system.service.message.mail.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.annotations.VisibleForTesting;
import com.sourceQ.system.domain.message.mail.SysMailTemplate;
import com.sourceQ.system.dto.message.MailTemplatePageReqDTO;
import com.sourceQ.system.dto.message.MailTemplateSaveReqDTO;
import com.sourceQ.system.mapper.message.mail.SysMailTemplateMapper;
import com.sourceQ.system.service.message.mail.SysMailTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static com.sourceQ.common.core.constant.ErrorCodeConstants.MAIL_TEMPLATE_CODE_EXISTS;
import static com.sourceQ.common.core.constant.ErrorCodeConstants.MAIL_TEMPLATE_NOT_EXISTS;
import static com.sourceQ.common.core.utils.ExceptionUtil.exception;

/**
 * @author: SourceQ
 * @create: 2024-04-18 17:49
 * @Description:
 */
@Service
public class SysMailTemplateServiceImpl extends ServiceImpl<SysMailTemplateMapper, SysMailTemplate> implements SysMailTemplateService {

    /**
     * 正则表达式，匹配 {} 中的变量
     */
    private static final Pattern PATTERN_PARAMS = Pattern.compile("\\{(.*?)}");
    @Override
    public Long createMailTemplate(MailTemplateSaveReqDTO createReqVO) {
        //校验编码
        validateCodeUnique(null,createReqVO.getCode());
        SysMailTemplate sysMailTemplate = new SysMailTemplate();
        BeanUtils.copyProperties(createReqVO,sysMailTemplate);
        sysMailTemplate.setParams(parseTemplateContentParams(sysMailTemplate.getContent()));
        baseMapper.insert(sysMailTemplate);
        return null;
    }

    @Override
    public void updateMailTemplate(MailTemplateSaveReqDTO updateReqVO) {
        SysMailTemplate sysMailTemplate = validateMailTemplateExists(updateReqVO.getId());
        validateCodeUnique(updateReqVO.getId(),updateReqVO.getCode());
        BeanUtils.copyProperties(updateReqVO,sysMailTemplate);
        sysMailTemplate.setParams(parseTemplateContentParams(updateReqVO.getContent()));
        updateById(sysMailTemplate);
    }

    @Override
    public void deleteMailTemplate(Long id) {
        validateMailTemplateExists(id);
        baseMapper.deleteById(id);
    }

    @Override
    public SysMailTemplate getMailTemplate(Long id) {
        return validateMailTemplateExists(id);
    }

    @Override
    public IPage<SysMailTemplate> getMailTemplatePage(Page page,MailTemplatePageReqDTO pageReqVO) {
        return baseMapper.getMailTemplatePage(page,pageReqVO);
    }

    @Override
    public List<SysMailTemplate> getMailTemplateList() {
        return baseMapper.selectList(Wrappers.<SysMailTemplate>lambdaQuery()
                .eq(SysMailTemplate::getDelFlag,"0"));
    }

    @Override
    public SysMailTemplate getMailTemplateByCodeFromCache(String code) {
        return baseMapper.selectOne(Wrappers.<SysMailTemplate>lambdaQuery()
                .eq(SysMailTemplate::getDelFlag,"0")
                .eq(SysMailTemplate::getCode,code));
    }

    @Override
    public String formatMailTemplateContent(String content, Map<String, Object> params) {
        return StrUtil.format(content, params);
    }

    @Override
    public long getMailTemplateCountByAccountId(Long accountId) {
        return baseMapper.selectCount(Wrappers.<SysMailTemplate>lambdaQuery()
                .eq(SysMailTemplate::getDelFlag,"0")
                .eq(SysMailTemplate::getAccountId,accountId));
    }

    /**
     * 校验code是否唯一
     * @param id
     * @param code
     */
    @VisibleForTesting
    void validateCodeUnique(Long id, String code) {
        SysMailTemplate template = baseMapper.selectOne(Wrappers.<SysMailTemplate>lambdaQuery().eq(SysMailTemplate::getCode,code).eq(SysMailTemplate::getDelFlag,"0"));
        if (template == null) {
            return;
        }
        // 存在 template 记录的情况下
        if (id == null // 新增时，说明重复
                || ObjUtil.notEqual(id, template.getId())) { // 更新时，如果 id 不一致，说明重复
            throw exception(MAIL_TEMPLATE_CODE_EXISTS);
        }
    }

    /**
     * 正则替换
     * @param content
     * @return
     */
    @VisibleForTesting
    public List<String> parseTemplateContentParams(String content) {
        return ReUtil.findAllGroup1(PATTERN_PARAMS, content);
    }

    /**
     * 校验数据是否存在
     * @param id
     */
    private SysMailTemplate validateMailTemplateExists(Long id) {
        SysMailTemplate sysMailTemplate = baseMapper.selectById(id);
        if ( sysMailTemplate == null) {
            throw exception(MAIL_TEMPLATE_NOT_EXISTS);
        }
        return sysMailTemplate;
    }
}
